package com.dgut.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.dgut.entity.Record;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExcelUtil {
    public static String writeExcel(HttpServletResponse response, List<Record> list) throws IOException {
        if (list.size() <= 0)
            return "no data to generate";
        String fileName = list.get(0).getClass().getSimpleName();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Disposition", "filename="+fileName+".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet = EasyExcel.writerSheet(0, "sheet").head(list.get(0).getClass()).build();
        excelWriter.write(list, sheet);
        excelWriter.finish();
        return "file:" + fileName + ".xlsx generated";
    }
}
